<template>
  <div class="share-card-box" :class="`is-${type}`">
    <!-- 调试时可注释掉以下两行 -->
    <!-- <img :src="resultImg[type]" v-show="resultImg[type]" class="sharepic" /> -->
    <img :src="resultImg" v-show="resultImg" class="sharepic" />
    <div class="hidden">
      <!-- for test 调试时打开 -->
      <!-- <div> -->
      <div ref="content" class="canvas-content">
        <!-- 模板1 -->
        <div
          class="template1"
          :style="
            type == 1
              ? {
                  backgroundImage: 'url(' + posterFirst + ')',
                }
              : type == 2
              ? {
                  backgroundImage: 'url(' + posterSencond + ')',
                }
              : {
                  backgroundImage: 'url(' + posterThird + ')',
                }
          "
        >
          <div class="baseinfo">
            <p class="time">{{ currentTime }}</p>
            <p class="jobTitle first" v-if="type === 1">以梦为马，驰骋天地， 寻找发光的你。</p>
            <div v-if="type === 2">
              <p class="jobTitle second">
                天青色等烟雨,
                <br />
                而我在等你。
              </p>
            </div>
            <div v-if="type === 3">
              <p class="jobTitle third">
                确认过眼神，
                <br />
                你就是那个对的人。
              </p>
            </div>
            <div class="qrcode">
              <canvas id="canvas"></canvas>
            </div>
            <div class="userInfo">
              <div class="item">
                <p class="price">
                  {{ data.showPrice == '面议' ? data.showPrice : '¥ ' + data.showPrice }}
                </p>
                <div class="location">
                  <div class="image">
                    <img src="../assets/images/location.png" />
                  </div>
                  <p class="place">{{ data.city }}</p>
                </div>
              </div>
              <p class="title">
                {{ data.title }}
              </p>
              <div class="item-detail">
                <div class="avatar" v-if="data.user.avatar">
                  <img
                    :src="data.user.avatar | imgSize(80, 80)"
                    crossorigin="anonymous"
                    ref="avatar"
                    key="imgR"
                    @load="finishLoad"
                    @error="avatarError"
                  />
                  <div
                    class="vlog"
                    :style="{
                      'background-image':
                        'url(' + ['', authPersonPic, authTeamPic][data.user.identified] + ')',
                    }"
                  ></div>
                </div>
                <div class="info">
                  <p v-if="data.user.nickname">
                    {{ data.user.nickname }}
                  </p>
                  <div class="info-item" v-if="data.user.nickname">
                    <p>{{ data.user.profession }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import QRCode from 'qrcode';
  import html2canvas from 'html2canvas';

  export default {
    props: {
      type: {
        type: [Number, String],
        default: 1,
      },
      url: {
        type: String,
      },
      data: {
        type: Object,
        require: true,
      },
      query: {
        type: Object,
      },
    },
    data() {
      return {
        cover: '',
        // resultImg: {},
        resultImg: '',
        currentTime: '',
        // posterFirst: 'https://ketang-pub.movtile.com/res/poster-1.jpg',
        posterFirst: require('../assets/images/poster-1.jpg'),
        posterSencond: require('../assets/images/poster-2.jpg'),
        posterThird: require('../assets/images/poster-3.jpg'),
        authPersonPic: require('../assets/images/icon-auth.png'),
        authTeamPic: require('../assets/images/icon-auth2.png'),
        loading: true,
        imgR: '',
      };
    },
    components: {},
    watch: {
      type() {
        if (this.loading == false) {
          this.makeImage();
        }
      },
    },
    mounted() {
      //获取当前时间
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      if (month < 10) {
        month = '0' + month;
      }
      if (day < 10) {
        day = '0' + day;
      }
      this.currentTime = year + ' / ' + month + ' / ' + day;
      this.makeImage();
    },
    methods: {
      finishLoad() {
        this.makeImage();
      },
      avatarError() {
        var num = 10;
        const cid = setInterval(() => {
          num -= 1;
          if (num == 0) {
            clearInterval(cid);
          }
          this.$refs['avatar'].setAttribute(
            'src',
            this.$refs['avatar'].getAttribute('src') + '&_=' + Math.random(),
          );
          this.makeImage();
          this.imgR = Math.random();
        }, 200);
        // alert(this.$refs['avatar'].getAttribute('src') + '&_=' + Math.random());
      },
      makeImage() {
        this.$nextTick(() => {
          const p1 = this.makeQrcode(this.url);
          // const p2 = this.getBase64Image(this.posterFirst, 'posterFirst');
          // const p3 = this.getBase64Image(this.posterSencond, 'posterSencond');
          // const p4 = this.getBase64Image(this.posterThird, 'posterThird');
          // let pArr = [p1, p2, p3, p4];
          let pArr = [p1];
          Promise.all(pArr).then(() => {
            this.eleToImg();
          });
        });
      },
      eleToImg() {
        // if (this.resultImg[this.type]) {
        //   this.$appService.setNav({
        //     title: '分享海报',
        //     handleClose: false,
        //     shareInfo: {
        //       image: this.resultImg[this.type],
        //     },
        //   });
        //   this.$emit('shareImageReady');
        //   return;
        // }
        html2canvas(this.$refs.content, {
          useCORS: true,
          scrollY: 0,
        })
          .then((canvas) => {
            // this.$set(this.resultImg, this.type, canvas.toDataURL());
            this.resultImg = canvas.toDataURL();
            this.loading = false;
            this.$emit('shareImageReady');
            this.$appService.setNav({
              title: '分享海报',
              handleClose: false,
              shareInfo: {
                // image: this.resultImg[this.type],
                image: this.resultImg,
              },
            });
          })
          .catch((err) => {
            console.log(err);
          })
          .finally(() => {
            this.loading = false;
          });
      },
      // 生成的二维码内容，可以添加变量
      makeQrcode(text) {
        return new Promise((resolve, reject) => {
          if (!text) {
            reject();
          }
          const canvas = document.getElementById('canvas');
          let config = {
            type: 'image/png',
            width: 200,
            height: 200,
            color: {
              light: 'ffffff00',
              dark: '00000072',
            },
            margin: 0,
          };
          QRCode.toCanvas(canvas, text, config, (error) => {
            if (error) {
              console.error(error);
              reject();
            }
            resolve();
          });
        });
      },
      getBase64Image(imgurl, key) {
        return new Promise((resolve, reject) => {
          var img = new Image();
          img.setAttribute('crossOrigin', 'anonymous');
          var canvas = document.createElement('canvas');
          let _imgurl = imgurl;
          switch (key) {
            // case 'cover':
            //   if (this.type === 1) {
            //     _imgurl = imgurl + '?x-oss-process=image/resize,m_fill,w_750,h_422';
            //     canvas.width = 750;
            //     canvas.height = 422;
            //   }
            //   break;
            default:
              //这个设置不能丢，否者会成为canvas默认的300*150的大小
              canvas.width = 650;
              canvas.height = 1155;
          }
          img.src = _imgurl;
          var ctx = canvas.getContext('2d');
          img.onload = () => {
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            this.$set(this, key, canvas.toDataURL());
            resolve();
          };
          img.onerror = (err) => {
            // 图片 url 不存在的时候就让页面继续加载吧。。
            resolve();
          };
        });
      },
    },
  };
</script>

<style lang="less">
  .share-card-box {
    width: 650px;
    height: 1160px;
    overflow: hidden;
    border-radius: 20px;
    .template1 {
      // width: 670px;
      // height: 938px;
      // overflow: hidden;
      height: 100%;
      width: 100%;
    }
    .sharepic {
      width: 100%;
      height: 100%;
      -webkit-touch-callout: default !important;
    }
    .hidden {
      // opacity: 0;
      position: fixed;
      left: 30000px;
      top: 30px;
      z-index: 20;
    }
    .canvas-content {
      overflow: hidden;
      width: 650px;
      height: 1155px;
      background-color: #f7f7f7;
      // border-radius: 20px;
      .baseinfo {
        padding: 0 60px;
      }
      .time {
        padding: 50px 0px;
        font-size: 36px;
        font-family: DIN;
        color: #ffffff;
      }
      .jobTitle {
        padding-top: 42px;
        font-size: 53px;
        font-family: PingFang SC;
        font-weight: 800;
        line-height: 90px;
        white-space: initial;
      }
      .first {
        color: #795c4e;
      }
      .second {
        color: #416d73;
      }
      .third {
        color: #707070;
      }
      .userInfo {
        margin-top: 168px;
        padding: 0 8px;
        .item {
          display: flex;
          justify-content: space-between;
        }
        .price {
          font-size: 40px;
          font-family: DIN;
          // font-weight: bold;
          color: #2247ff;
        }
        .location {
          display: flex;
          align-items: center;
          .image {
            width: 25px;
            height: 26px;
          }
          img {
            width: 100%;
            height: 100%;
            display: block;
          }
        }

        .place {
          margin-left: 5px;
          display: flex;
          align-items: center;
          font-size: 28px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #111111;
          // &:before {
          //   content: '';
          //   width: 30px;
          //   height: 25px;
          //   display: block;
          //   background: url(../assets/images/location.png);
          //   background-size: 26px;
          //   background-repeat: no-repeat;
          // }
        }
        .title {
          margin-top: 10px;
          font-size: 31px;
          font-family: PingFang SC;
          font-weight: 800;
          color: #111111;
          line-height: 47px;
          white-space: initial;
          // word-break: break-all;
          // text-overflow: ellipsis;
          // overflow: hidden;
          // display: -webkit-box; /**对象作为伸缩盒子模型展示**/
          // -webkit-box-orient: vertical; /**设置或检索伸缩盒子对象的子元素的排列方式**/
          // -webkit-line-clamp: 2; /**显示的行数**/
        }
        .item-detail {
          display: flex;
          // margin-top: 35px;
          position: absolute;
          bottom: 100px;
        }
        .avatar {
          width: 80px;
          height: 80px;
          overflow: visible;
          position: relative;
          img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
          }
          .vlog {
            content: '';
            display: block;
            position: absolute;
            width: 27px;
            height: 27px;
            background-size: 27px;
            background-repeat: no-repeat;
            background-size: contain;
            border-radius: 50%;
            left: 60px;
            bottom: 0px;
            z-index: 999;
          }
        }
        .info {
          justify-content: stretch;
          margin-left: 20px;
          width: 420px;
          p {
            white-space: nowrap;
            word-break: break-all;
            text-overflow: ellipsis;
            overflow: hidden;
            font-size: 28px;
            font-family: PingFang SC;
            font-weight: 800;
            color: #111111;
          }
          .info-item {
            display: flex;
            margin-top: 10px;

            p {
              font-size: 24px;
              font-family: PingFang SC;
              font-weight: 400;
              color: #888888;
              white-space: nowrap;
              word-break: break-all;
              text-overflow: ellipsis;
              overflow: hidden;
            }
          }
        }
      }
      .desc {
        font-size: 24px;
        color: #111111;
        line-height: 30px;
        height: 60px;
      }
      .bottom-info {
        display: flex;
        justify-content: space-between;
      }
      .statis {
        .price {
          display: flex;
          margin-bottom: 40px;
          align-items: baseline;
          flex-wrap: wrap;
          width: 33.5rem;
          .origin-price {
            font-size: 24px;
            height: 24px;
            font-weight: 400;
            color: #888888;
            margin-right: 20px;
            position: relative;
            line-height: 1;
            .line-through {
              position: absolute;
              width: 100%;
              height: 1px;
              top: 50%;
              left: 0;
              background-color: #888888;
            }
          }
          .sale-price {
            font-size: 40px;
            font-family: DIN;
            font-weight: 400;
            color: #2247ff;
          }
        }
        .playcnt {
          font-size: 24px;
          font-weight: 400;
          color: #888888;
        }
      }
      .qrcode {
        text-align: center;
        width: 20rem;
        flex-shrink: 0;
        canvas {
          width: 200px;
          height: 200px;
        }
        .qrcode-tips {
          margin-top: 17px;
          font-size: 22px;
          height: 22px;
          line-height: 1;
          font-weight: 400;
          color: #121212;
        }
      }

      .template1 {
        // background: url(https://ketang-pub.movtile.com/res/poster-1.jpg);
        background-size: contain;
        background-repeat: no-repeat;
        position: relative;
        .desc {
          margin-bottom: 25px;
        }
        .statis {
          margin-top: 10px;
        }
        .qrcode {
          padding-top: 60px;
          // position: absolute;
          // right: 40px;
          // bottom: 40px;
          margin: 0 auto;
          background-color: transparent;
        }
        .qrcode-tips {
          margin-top: 17px;
        }
      }
    }
  }
</style>
